package com.liqi.web.controller.openapi.middleware;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.utils.DateUtils;
import com.liqi.deployment.domain.DvDeployment;
import com.liqi.deployment.domain.DvOperationUser;
import com.liqi.deployment.service.IDvDeploymentService;
import com.liqi.monitor.domain.DvFaultLog;
import com.liqi.monitor.service.IDvFaultLogService;
import com.liqi.sms.domain.SysShortMessage;
import com.liqi.sms.service.ISysShortMessageService;
import com.liqi.system.domain.SysMail;
import com.liqi.system.service.ISysMailService;
import com.liqi.system.service.device.IDvOperationUserService;

/**
 * 异常上报Controller
 *
 * @author ymh
 * @date 2022-03-01
 */
@RestController
@RequestMapping("/openApi/middleware")
public class DvExceptionInfoController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(DvExceptionInfoController.class);

    @Autowired
    private IDvFaultLogService dvFaultLogService;

    @Autowired
    private ISysShortMessageService sysShortMessageService;

    @Autowired
    private ISysMailService SysMailService;
    @Autowired
    private IDvDeploymentService dvDeploymentService;
    @Autowired
    private IDvOperationUserService dvOperationUserService;

    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.CarbonCopy}")
    private String CarbonCopy;

    @PostMapping(value = "/saveExceptionInfo")
    public AjaxResult exceptionInfo(@RequestBody Map<String, String> requestParam ) {
        String deviceId = requestParam.get("deviceId").toString();
        String deviceCode = requestParam.get("deviceCode").toString();
        String deviceName = requestParam.get("deviceName").toString();
        String errorCode = requestParam.get("errorCode").toString();
        String errorMessage = requestParam.get("errorMessage").toString();
        String moduleCode = requestParam.get("moduleCode")==null?"":requestParam.get("moduleCode").toString();
        String moduleName = requestParam.get("moduleName")==null?"":requestParam.get("moduleName").toString();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(StringUtils.isBlank(deviceId) ) {
            logger.error("设备Id不能为空");
            return AjaxResult.error("设备Id不能为空。" + JSON.toJSONString(deviceId));
        }
        if( StringUtils.isBlank(deviceCode)) {
            logger.error("设备代码不能为空");
            return AjaxResult.error("设备代码不能为空。" + JSON.toJSONString(deviceCode));
        }
        if( StringUtils.isBlank(deviceName)) {
            logger.error("设备名称不能为空");
            return AjaxResult.error("设备名称不能为空。" + JSON.toJSONString(deviceName));
        }
        if( StringUtils.isBlank(errorCode)) {
            logger.error("异常代码不能为空");
            return AjaxResult.error("异常代码不能为空。" + JSON.toJSONString(errorCode));
        }
        if( StringUtils.isBlank(errorMessage)) {
            logger.error("异常信息不能为空");
            return AjaxResult.error("异常信息不能为空。" + JSON.toJSONString(errorMessage));
        }
        DvFaultLog dvFaultLog = new DvFaultLog();
        dvFaultLog.setDeviceId(deviceId);
        dvFaultLog.setDeviceCode(deviceCode);
        dvFaultLog.setDeviceName(deviceName);
        dvFaultLog.setErrorCode(errorCode);
        dvFaultLog.setErrorMessage(errorMessage);
        dvFaultLog.setEquipmentFalutType("0");
        dvFaultLog.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));
        DvDeployment dvDeployment = dvDeploymentService.getByDeviceId(deviceId);
        if(dvDeployment ==null){
            logger.error("自编设备号投放信息不存在");
            return AjaxResult.error("自编设备号投放信息不存在");
        }
        dvFaultLog.setDeptId(dvDeployment.getDeptId());
        dvFaultLog.setCreateUserId(dvDeployment.getCreateUserId());
        String deploymentAddress = dvDeployment.getDeploymentAddress();
        DvOperationUser dvOperationUser = dvOperationUserService.selectDvOperationUserByOperationUserName(dvDeployment.getOperationUserName(), dvDeployment.getOperationUserCode());
        if(dvOperationUser==null){
            logger.error("运维人员信息不存在");
            return AjaxResult.error("运维人员信息不存在");
        }

        SysMail sysMail=new SysMail();
        sysMail.setMailFrom(from);
        sysMail.setMailToList(dvOperationUser.getEmail());
        sysMail.setCcList(CarbonCopy);
        sysMail.setSendFlag("0");
        sysMail.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));
        Map<String,Object> map = new HashMap<>();
        map.put("operationUserName", dvDeployment.getOperationUserName());
        map.put("nowTime",df.format(new Date()));
        map.put("deviceId",deviceId);
        map.put("deploymentName", dvDeployment.getDeploymentName());
        map.put("deploymentAddress", dvDeployment.getAncestorsName()+ dvDeployment.getDeploymentAddress());
        map.put("errorMessage",errorMessage);

        // 新建短信实体，并插入到短信实体数据库
        SysShortMessage sysShortMessage = new SysShortMessage();
        sysShortMessage.setPhoneNumbers(dvOperationUser.getPhoneNumber());
        sysShortMessage.setCreateTime(DateUtils.getNowDate());
        sysShortMessage.setSendFlag("0");


            map.put("reportType","运行中上报");
            String result1 = JSONUtils.toJSONString(map);
                sysMail.setBody(result1);
                sysMail.setCreateBy("运行中上报");

            sysShortMessage.setTemplateParam(result1);
            sysShortMessage.setCreateBy("运行中上报");

//        dvExceptionInfoService.insertDvExceptionInfo(dvExceptionInfo);
        // 存储到dv_equipment_fault_log
//        DvEquipmentFaultLog dvEquipmentFaultLog = new DvEquipmentFaultLog();
//        BeanUtils.copyProperties(dvExceptionInfo, dvEquipmentFaultLog);
        dvFaultLogService.insertDvFaultLog(dvFaultLog);
        SysMailService.insertSysMail(sysMail);
        sysShortMessageService.insertSysShortMessage(sysShortMessage);
        AjaxResult result = AjaxResult.success("操作成功！");
        return result;
}
}
